package top.gbiot.redis.runner;


import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.gbiot.common.domain.DataMap;
import top.gbiot.redis.mapper.RedisMapper;
import top.gbiot.redis.util.RedisUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * springboot 允许实现CommandLineRunner接口的类程序启动后run方法中做一些事情，比如加载缓存.
 */
@Component
@Order(value = 2)
public class InitRedisCacheRunner implements CommandLineRunner {
    protected   final Logger log= LoggerFactory.getLogger(getClass());
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisMapper redisMapper;

    @Override
    public void run(String... args) throws Exception {
        log.info("InitRedisCacheRunner加载缓存信息start>>>>>>>");
       //可以从数据库加载配置信息到缓存
/*        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("1","温湿度传感器");
        dataMap.put("2","光照传感器");
        dataMap.put("3","监控'设备");
        redisUtils.hmset("deviceCache",dataMap);*/
//        List<DataMap> deviceCacheList = redisMapper.selectAllDevice4Cache();
//        for (int i=0;i<deviceCacheList.size();i++){
//            Map<String,Object> deviceMap=deviceCacheList.get(i);
//            redisUtils.hmset("deviceCache"+i,deviceMap);
//        }
       /* for (Map<String,Object> deviceMap:deviceCacheList) {
            redisUtils.hmset("deviceCache",deviceMap);
        }*/
        //redisUtils.set("deviceCache",JSON.toJSONString(deviceCacheList));
       /* List<String> list = new ArrayList<>();
        list.add("123");
        list.add("456");
        list.add("789");
        redisUtils.lSet("ll", list);*/
        //1.查询并缓存所有项目信息以及对应的ApiKey  只有正确ApiKey才允许数据入库
        List<DataMap> apiKeyCacheList = redisMapper.selectAllApiKey4Cache();
        boolean apiKeyResult = redisUtils.set("apiKeyCache",JSON.toJSONString(apiKeyCacheList));
        if(apiKeyResult){
            log.info("加载apiKey缓存信息成功！");
        }else{
            log.warn("加载apiKey缓存信息失败！");
        }
        //2.查询并缓存所有设备信息
        List<DataMap> deviceCacheList = redisMapper.selectAllDevice4Cache();
        boolean deviceResult=redisUtils.set("deviceCache",JSON.toJSONString(deviceCacheList));
        if(deviceResult){
            log.info("加载设备缓存信息成功！");
        }else{
            log.warn("加载设备缓存信息失败！");
        }

        log.info("InitRedisCacheRunner加载缓存信息End<<<<<<<<");
    }
}
